import { useUserStore } from '@/stores'
import { createRouter, createWebHistory } from 'vue-router'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 去除进度条右上角的圆环效果
NProgress.configure({
  showSpinner: false,
})

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      component: () => import('@/views/Login/index.vue'),
      meta: { title: '登录' },
    },
    {
      path: '/',
      redirect: '/home',
      component: () => import('@/views/Layout/index.vue'),
      children: [
        {
          path: 'home',
          component: () => import('@/views/Home/index.vue'),
          meta: { title: '首页' },
        },
        {
          path: 'article',
          component: () => import('@/views/Article/index.vue'),
          meta: { title: '健康百科' },
        },
        {
          path: 'notify',
          component: () => import('@/views/Notify/index.vue'),
          meta: { title: '消息中心' },
        },
        {
          path: 'user',
          component: () => import('@/views/User/index.vue'),
          meta: { title: '个人中心' },
        },
      ],
    },
    {
      path: '/user/patient',
      component: () => import('@/views/User/PatientPage.vue'),
      meta: { title: '家庭档案' },
    },
  ],
})

// 添加访问权限控制
router.beforeEach((to) => {
  // 用户仓库
  const store = useUserStore()

  NProgress.start()
  // 不需要登录的页面, 白名单列表
  const wihteList = ['/login']
  // 如果没有登录且不在白名单内, 去登录
  if (!store.user?.token && !wihteList.includes(to.path)) return '/login'
  // 如果有token ,且去登录页 统一拦截到首页 '/'
  if (store.user?.token && to.path === '/login') return '/'

  // 其他的直接放行
})

router.afterEach((to) => {
  // 4.1 关闭进度条效果
  NProgress.done()
  document.title = `Jay-医院-${to.meta.title || ''}`
})

export default router
